<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="设置坐标"
    width="1000px"
    :canFullscreen="false"
    @cancel="handleClose"
    @ok="handleOk"
    okText="确定"
  >
    <div id="container" style="width: 100%; height: 600px"></div>
    <div class="info">
      <Select
        show-search
        v-model="value"
        placeholder="请输入地址"
        style="width: 250px"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        :not-found-content="null"
        @search="autoInput"
        @change="handleChange"
      >
        <SelectOption v-for="d in data" :value="d.name" :key="d.id">
          {{ d.name }}
        </SelectOption>
      </Select>
    </div>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, watch } from 'vue';
  import { Select, SelectOption } from 'ant-design-vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { useI18n } from '@/hooks/web/useI18n';
  import { propTypes } from '@/utils/propTypes';

  const props = {
    circled: { type: Boolean, default: true },
    infoData: propTypes.object.def({}),
    visible: propTypes.bool.def(false),
  };

  export default defineComponent({
    name: 'CropperModal',
    components: { BasicModal, Select, SelectOption },
    props,
    emits: ['ok', 'register', 'cancel'],
    setup(props, { emit }) {
      const [register, { closeModal }] = useModalInner();
      const { t } = useI18n();

      let map: any = null;
      let aMap: any = null;
      let geocoder;
      let infoWindow;
      let lng;
      let lat;
      let address;

      const value = ref();
      const data = ref([]);

      watch(
        () => props.visible,
        (val) => {
          if (val) mapInit();
        },
      );

      //初始化地图
      function mapInit() {
        console.log('地图初始化');
        AMapLoader.load({
          key: 'b552ef3896f065585864ab940b356589', // 申请好的Web端开发者Key，首次调用 load 时必填
          version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.Geocoder', 'AMap.AutoComplete'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
          .then((AMap) => {
            aMap = AMap;
            map = new AMap.Map('container', {
              //设置地图容器id
              viewMode: '3D', //是否为3D地图模式
              zoom: 5, //初始化地图级别
              center: [105.602725, 37.076636], //初始化地图中心点位置
            });

            geocoder = new AMap.Geocoder({
              radius: 1000, // 范围，默认：500
            });

            map.on('complete', () => {
              infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -35) });
              if (props.infoData.longitude) {
                createMarker();
              }
              clickOn();
            });

            // map?.on('click', function (ev) {
            //   console.log('ev--->', ev);
            // });
          })
          .catch((e) => {
            console.log(e);
          });
      }

      function clickOn() {
        map.on('click', showInfoClick);
      }

      function showInfoClick(e) {
        // console.log('e--->', e);
        lng = e.lnglat.getLng();
        lat = e.lnglat.getLat();
        createMarker();
      }

      // 展示信息
      function markerClick(e) {
        infoWindow.setContent(e.target.content);
        infoWindow.open(map, e.target.getPosition());
      }

      function createMarker() {
        map.clearMap();
        var marker = new aMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: [lng, lat],
        });
        map.add(marker);
        map.setCenter([lng, lat]); //设置地图中心点
        var lnglat = [lng, lat];

        // console.log('lnglat--->', lnglat);

        marker.setPosition(lnglat);

        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            // console.log(result.regeocode);
            address = result.regeocode.formattedAddress;
            marker.content = address;
            marker.emit('click', { target: marker });
          } else {
            // _this.$message.error('根据经纬度查询地址失败');
          }
        });
        marker.on('click', markerClick);
      }

      function handleClose() {
        emit('cancel');
        closeModal();
      }

      async function handleOk() {
        var params = {
          longitude: lng,
          latitude: lat,
          address: address,
        };
        emit('ok', params);
        closeModal();
      }

      // 获取输入提示信息
      function autoInput(val) {
        // aMap.plugin('AMap.Autocomplete', function () {
        // 实例化Autocomplete
        var autoOptions = {
          city: '全国',
        };
        // console.log('aMap--->', aMap);

        var autoComplete = new aMap.AutoComplete(autoOptions);
        autoComplete.search(val, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          // console.log(result);
          data.value = result.tips;
        });
        // });
      }

      function handleChange(name) {
        let item: any = data.value.find((f: any) => f.name === name);
        if (!item?.location) return;
        lng = item.location.lng;
        lat = item.location.lat;
        createMarker();
      }

      return {
        t,
        register,
        handleClose,
        handleOk,
        value,
        data,
        autoInput,
        handleChange,
      };
    },
  });
</script>

<style lang="less" scoped>
  .info {
    position: absolute;
    top: 95px;
    left: 40px;
  }
</style>
